package com.lxq.cloud.ai.service;





import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import com.lxq.cloud.ai.entity.AudioResult;
import jakarta.annotation.PreDestroy;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import cn.hutool.core.io.FileUtil;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.cn;

@Slf4j
@Service
public class AudioServiceImpl implements AudioService, ApplicationRunner {
    private final SpeechSynthesisModel speechSynthesisModel;
    private static final String FILE_PATH = System.getProperty("user.dir") + File.separator + LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd-HH-mm-ss")) + ".wav";

    public AudioServiceImpl(SpeechSynthesisModel speechSynthesisModel) {

        this.speechSynthesisModel = speechSynthesisModel;
    }

    @Override
    public AudioResult genAudio(String textToSynthesize) {
        SpeechSynthesisResponse response = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(textToSynthesize)
        );
        ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
        return new AudioResult(FILE_PATH, byteBuffer.array());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        FileUtil.mkdir(Paths.get(FILE_PATH).getParent());
    }

    @PreDestroy
    public void destroy() {
        FileUtil.del(Paths.get(FILE_PATH));
    }
}